package com.kds.smarthome.job;

import com.kds.smarthome.entity.enums.JobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
public class SampleJob implements Job {


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
         // 获取当前状态
        String status = context.getJobDetail().getJobDataMap().getString("status");
        log.info("任务开始执行，当前状态: {}", status);

        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("测试定时任务执行 - 当前时间: {}", currentTime);

         // 获取任务参数
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        jobDataMap.forEach((key, value) -> {
            log.info("参数 {} = {}", key, value);
        });
          context.getJobDetail().getJobDataMap().put("status", JobStatus.NORMAL.getCode());

            } catch (Exception e) {
            // 发生异常时更新状态
            context.getJobDetail().getJobDataMap().put("status", JobStatus.ERROR.getCode());
            log.error("任务执行失败", e);
            throw new JobExecutionException(e);
        }
    }
}
